package com.zhm.demo.json;

import cn.hutool.core.io.FileUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.networknt.schema.JsonSchema;
import com.networknt.schema.JsonSchemaFactory;
import com.networknt.schema.SpecVersion;
import com.networknt.schema.ValidationMessage;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;
import java.nio.charset.Charset;
import java.util.Set;

@Slf4j
public class JsonValidationTest {

    private static final String SCHEMA_VALIDATION_FILE = "/validation.json";

    public static void main(String[] args) throws JsonProcessingException {
        URL resource = JsonValidationTest.class.getResource("/test.json");
        String s = FileUtil.readString(resource, Charset.forName("UTF-8"));
        System.out.println(s);
        // 创建ObjectMapper实例
        ObjectMapper mapper = new ObjectMapper();

        // 将字符串转换为JsonNode
        JsonNode jsonNode = mapper.readTree(s);

        JsonSchema jsonSchema =  JsonSchemaFactory
                .getInstance( SpecVersion.VersionFlag.V7 )
                .getSchema( JsonValidationTest.class.getResourceAsStream( SCHEMA_VALIDATION_FILE ) );

        Set<ValidationMessage> errors = jsonSchema.validate(jsonNode);
        if(errors.isEmpty()){
            log.info("event is valid");
        }else{
            log.info("event is invalid");
        }
        System.out.println(errors);
    }

}
